package com.kuangjia.student_ems.security;

import com.kuangjia.student_ems.entity.SalaryRecord;
import com.kuangjia.student_ems.entity.User;
import com.kuangjia.student_ems.mapper.SalaryRecordMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

@Component
public class SalarySecurity {
    @Autowired
    private SalaryRecordMapper salaryRecordMapper;

    /**
     * 判断当前用户是否有权限访问指定薪资记录
     * HR/部门经理有全部权限，普通用户只能访问自己的记录
     */
    public boolean hasRecordPermission(Long recordId, Authentication authentication) {
        if (authentication == null || authentication.getPrincipal() == null) {
            return false;
        }
        Object principal = authentication.getPrincipal();
        if (!(principal instanceof User user)) {
            return false;
        }
        // HR/部门经理有全部权限
        if (user.getRole() == User.UserRole.HR_ADMIN || user.getRole() == User.UserRole.DEPARTMENT_MANAGER) {
            return true;
        }
        // 普通用户只能访问自己的记录
        SalaryRecord record = salaryRecordMapper.selectById(recordId);
        return record != null && record.getUserId().equals(user.getId());
    }
} 